//
//  RegisteredViewController.m
//  suRead
//
//  Created by 龚浩植 on 15/11/12.
//  Copyright © 2015年 bao. All rights reserved.
//

#import "RegisteredViewController.h"
#import "ServiceNews.h"
#import "UIControl+Blocks.h"
#import "UIViewController+HUD.h"
#import "ServiceUserNew.h"

@interface RegisteredViewController ()<UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UIView *registeredPhoneView;
@property (strong, nonatomic) IBOutlet UIView *registeredVerificationCodeView;
@property (strong, nonatomic) IBOutlet UIView *registeredPwdView;

@property (strong, nonatomic) IBOutlet UITextField *registeredPhoneTextField;
@property (weak, nonatomic) IBOutlet UIButton *getCodeButton;
@property (strong, nonatomic) IBOutlet UITextField *registeredVerificationCodeTextField;
@property (strong, nonatomic) IBOutlet UITextField *registeredPwdTextField;

@property (strong, nonatomic) IBOutlet UINavigationItem *submitNavigationItem;



@end

@implementation RegisteredViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    __weak typeof(self) weak_self = self;
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:240/255.0f green:241/255.0f blue:242/255.0f alpha:1.0f];
    UIButton *buttonComment = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonComment.titleLabel.font = [UIFont systemFontOfSize:18.0f];
    buttonComment.frame = CGRectMake(0, 0, 50.0f, 25.0f);
    [buttonComment setTitle:@"提交" forState:UIControlStateNormal];
    [buttonComment setBackgroundColor:[UIColor redColor]];
    buttonComment.layer.cornerRadius = 10.0f;
    buttonComment.layer.masksToBounds = YES;
    UIBarButtonItem *submitItem = [[UIBarButtonItem alloc] initWithCustomView:buttonComment];
    [buttonComment addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {

        if([self.registeredVerificationCodeTextField.text isEqualToString:@""]){
            return [theAppDelegate alert:@"验证码不能为空!"];
        }

        if (!self.registeredPhoneTextField.text || self.registeredPhoneTextField.text.length != 11 || ![[self.registeredPhoneTextField.text substringToIndex:1] isEqualToString:@"1"]||![self validateNumber:self.registeredPhoneTextField.text])
        {
            [self showHUDText:@"手机号格式错误"];
            return;
        }

        if([self.registeredPwdTextField.text isEqualToString:@""]){
            return [theAppDelegate alert:@"密码不能为空!"];
        }
        if (![self validatePassword:self.registeredPwdTextField.text]) {
            return [theAppDelegate alert:@"密码格式不正确!"];
        }
        
        [self showHUDProgress:nil];

        [ServiceUserNew doRegister:self.registeredPhoneTextField.text
                          password:self.registeredPwdTextField.text
                              code:self.registeredVerificationCodeTextField.text success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
                                        [weak_self removeHUDProgress];
            [weak_self showHUDText:message];
            [weak_self.navigationController popToRootViewControllerAnimated:YES];
        } failure:^(NSString * _Nonnull message) {
            [weak_self removeHUDProgress];
            [weak_self showHUDText:message];
        }];

    }];
    self.submitNavigationItem.rightBarButtonItem = submitItem;
    
    self.registeredPhoneView.layer.borderColor = [UIColor colorWithRed:233/255.0f green:233/255.0f blue:233/255.0f alpha:1.0f].CGColor;
    self.registeredPhoneView.layer.borderWidth = 1.0f;
    
    self.registeredVerificationCodeView.layer.borderColor = [UIColor colorWithRed:233/255.0f green:233/255.0f blue:233/255.0f alpha:1.0f].CGColor;
    self.registeredVerificationCodeView.layer.borderWidth = 1.0f;
    
    self.registeredPwdView.layer.borderColor = [UIColor colorWithRed:233/255.0f green:233/255.0f blue:233/255.0f alpha:1.0f].CGColor;
    self.registeredPwdView.layer.borderWidth = 1.0f;
    
    [self.getCodeButton addTarget:self action:@selector(getCode:) forControlEvents:UIControlEventTouchUpInside];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

/*邮箱验证 MODIFIED BY HELENSONG*/
-(BOOL)isValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

/*手机号码验证 MODIFIED BY HELENSONG*/
-(BOOL) isValidateMobile:(NSString *)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //    NSLog(@"phoneTest is %@",phoneTest);
    return [phoneTest evaluateWithObject:mobile];
}

//用户名
- (BOOL) validateUserName:(NSString *)name
{
    NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return B;
}

//密码
- (BOOL) validatePassword:(NSString *)passWord
{
    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}

//昵称
- (BOOL) validateNickname:(NSString *)nickname
{
    NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,8}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:nickname];
}
- (IBAction)registeredBackItem:(id)sender
{
  [self.navigationController popViewControllerAnimated:YES];
  [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)getCode:(id)sender
{
    if (!self.registeredPhoneTextField.text || self.registeredPhoneTextField.text.length != 11 || ![[self.registeredPhoneTextField.text substringToIndex:1] isEqualToString:@"1"]||![self validateNumber:self.registeredPhoneTextField.text])
    {
        [self showHUDText:@"手机号格式错误"];
        return;
    }
    __weak typeof(self) weak_self = self;
    self.getCodeButton.userInteractionEnabled=NO;
    self.getCodeButton.alpha=0.4;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        weak_self.getCodeButton.userInteractionEnabled=YES;
        weak_self.getCodeButton.alpha=1.0f;
    });
    [self showHUDProgress:nil];
    
    [ServiceUserNew doGetPhoneCode:self.registeredPhoneTextField.text
                        success:^(id responseObject, NSString *message) {
                            [weak_self removeHUDProgress];
                            [weak_self showHUDText:message];
                        } failure:^(NSString *message) {
                            [weak_self removeHUDProgress];
                            [weak_self showHUDText:message];
                            weak_self.getCodeButton.userInteractionEnabled=YES;
                            weak_self.getCodeButton.alpha=1.0f;
                        }];
}
- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}
@end
